package com.zhenhao.xsq.ui.activity.login;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.provider.Settings;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.EncryptUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.orhanobut.logger.Logger;
import com.zhenhao.xsq.MainActivity;
import com.zhenhao.xsq.R;
import com.zhenhao.xsq.application.AppConfig;
import com.zhenhao.xsq.base.BaseActivity;
import com.zhenhao.xsq.contain.Contains;
import com.zhenhao.xsq.data.api.API;
import com.zhenhao.xsq.db.green.UserLoginInfo;
import com.zhenhao.xsq.entity.BaseDataEntity;
import com.zhenhao.xsq.entity.BaseEntity;
import com.zhenhao.xsq.entity.login.UserEntity;
import com.zhenhao.xsq.netsdk_demo.CLocalDevLogin;
import com.zhenhao.xsq.ui.activity.home.HomeActivity;
import com.zhenhao.xsq.ui.activity.login.component.DaggerLoginComponent;
import com.zhenhao.xsq.ui.activity.login.contract.LoginContract;
import com.zhenhao.xsq.ui.activity.login.module.LoginModule;
import com.zhenhao.xsq.ui.activity.login.presenter.LoginPresenter;
import com.zhenhao.xsq.ui.activity.video.VideoActivity;
import com.zhenhao.xsq.ui.activity.web.WebSatisficingActivity;
import com.zhenhao.xsq.utils.DbUtils;
import com.zhenhao.xsq.utils.DialogUtils;
import com.zhenhao.xsq.utils.SpSaveUtils;
import com.zhenhao.xsq.utils.SpUtil;
import com.zhenhao.xsq.utils.ToastUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import androidx.core.app.NotificationManagerCompat;
import androidx.core.content.ContextCompat;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * @author xlei
 * @Package com.example.rxdemo.ui.activity.login
 * @Description: $description
 * @date 2019/01/03 14:52:55
 */

public class LoginActivity extends BaseActivity implements LoginContract.View {

    @Inject
    LoginPresenter mPresenter;

    @BindView(R.id.tv_register)
    TextView tvRegister;
    @BindView(R.id.et_account)
    EditText etAccount;
    @BindView(R.id.img_clear)
    ImageView imgClear;
    @BindView(R.id.et_pwd)
    EditText etPwd;
    @BindView(R.id.iv_show_password)
    CheckBox ivShowPassword;
    @BindView(R.id.ll_mm)
    LinearLayout llMm;
    @BindView(R.id.tv_forget_pwd)
    TextView tvForgetPwd;
    @BindView(R.id.bt_go)
    Button btGo;


    private CountDownTimer countDownTimer;
    private String accout;
    private String pwd;
    private String code;
    private String projectNumber;
    private int loginType = 0;//1密码 2验证码


    @Override
    protected void initView() {
        needFront = true;
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        //        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        autolayout.setVisibility(View.GONE);
        //打开通知设置界面
//        openNotification();

//        if (AppUtils.getAppVersionCode() > SpUtil.getInt(this, Contains.SP_APP_VERSION, 0)) {
//            showHintDialog();
//        }//
//
//        if (SpUtil.getInt(this, Contains.SP_APP_ISFIRST, 0) == 0) {
//            showHintDialog();
//        }
    }


    @Override
    protected void initData() {
        //设置密码可不可见
        ivShowPassword.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    etPwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance
                            ());
                    etPwd.setSelection(etPwd.getText().length());
                } else {
                    etPwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    etPwd.setSelection(etPwd.getText().length());
                }
            }
        });
        etAccount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                //清空按钮显示与隐藏
                if (TextUtils.isEmpty(editable.toString())) {
                    imgClear.setVisibility(View.INVISIBLE);
                } else {
                    imgClear.setVisibility(View.VISIBLE);
                }
                //手机号改变清除项目信息
                if (!TextUtils.isEmpty(projectNumber)) {
                    projectNumber = "";
                }
            }
        });


    }


    @Override
    protected void setupActivityComponent() {
        DaggerLoginComponent
                .builder()
                .appComponent(((AppConfig) getApplication()).getApplicationComponent())
                .loginModule(new LoginModule(this))
                .build()
                .inject(this);
    }

    @Override
    public void setPresenter(LoginContract.LoginContractPresenter presenter) {
        mPresenter = (LoginPresenter) presenter;
    }

    @Override
    public void showProgressDialog() {
        progressDialog.show();
    }

    @Override
    public void closeProgressDialog() {
        progressDialog.hide();
    }

    @Override
    public void loginSuccess(BaseDataEntity loginEntity) {
        //登录成功 保存token等
        SpSaveUtils.putAccessToken(loginEntity.getData());
//        SpSaveUtils.putRefreshToken(loginEntity.getList().getRefresh_token());
        //拉取用户  信息
        mPresenter.getUserInfo();
    }

    @Override
    public void loginFail() {

    }


    @Override
    public void getUserInfoSuccess(UserEntity userEntity) {

        SpUtil.putInt(this, Contains.SP_APP_VERSION, AppUtils.getAppVersionCode());
        SpUtil.putInt(this, Contains.SP_APP_ISFIRST, 1);

        //保存用户信息
        SpSaveUtils.putUserInfoJson(GsonUtils.toJson(userEntity));
        //保存业主信息
        SpSaveUtils.putYzInfoJson(GsonUtils.toJson(userEntity.getData().getYezhuVo()));
        //保存业主id
        SpSaveUtils.putUserId(userEntity.getData().getYezhuVo().getYezhuId() + "");

        if (loginType == 1) {//登录方式为密码
            new Thread(new Runnable() {
                @Override
                public void run() {
                    saveUserInfo(userEntity);//保存用户数据到数据库中，用于切换账户

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            showFwSelect();
                        }
                    });
                }
            }).start();
        } else {
            showFwSelect();
        }
    }

    /**
     * 设置当前房屋
     */
    private void showFwSelect() {
        List<String> fwList = new ArrayList<>();
        final UserEntity userEntity = SpSaveUtils.getUserInfoJson();
        if (userEntity != null && userEntity.getData() != null) {
            if (userEntity.getData().getHouseVos() != null && userEntity.getData().getHouseVos().size() > 0) {
                if (userEntity.getData().getHouseVos().size() == 1) {
                    //只有一条信息默认保存 （不谈提示框）保存当前房屋id房屋信息
                    SpSaveUtils.putFwId(userEntity.getData().getHouseVos().get(0).getFangwuId() + "");
                    SpSaveUtils.putFwBh(userEntity.getData().getHouseVos().get(0).getFangwuBh() + "");
                    SpSaveUtils.putFwInfoJson(GsonUtils.toJson(userEntity.getData().getHouseVos().get(0)));

                    new Thread() {
                        public void run() {
                            try {
                                sleep(500);
                                startActivty(HomeActivity.class);
                                finish();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }.start();
//                    startActivty(HomeActivity.class);
//                    finish();
                } else {
                    for (int i = 0; i < userEntity.getData().getHouseVos().size(); i++) {
                        fwList.add(userEntity.getData().getHouseVos().get(i).getQiqu()
                                + userEntity.getData().getHouseVos().get(i).getLoudong() + "栋"
                                + userEntity.getData().getHouseVos().get(i).getDanyuan() + "单元"
                                + userEntity.getData().getHouseVos().get(i).getFanghao() + "房号");
                    }
                    DialogUtils.showFwDialog(this, fwList, new DialogUtils.onTreeSelect() {
                        @Override
                        public void onTreeSelect(String str, int position) {
                            //保存当前房屋id房屋信息
                            SpSaveUtils.putFwId(userEntity.getData().getHouseVos().get(position).getFangwuId() + "");
                            SpSaveUtils.putFwBh(userEntity.getData().getHouseVos().get(position).getFangwuBh() + "");
                            SpSaveUtils.putFwInfoJson(GsonUtils.toJson(userEntity.getData().getHouseVos().get
                                    (position)));

                            new Thread() {
                                public void run() {
                                    try {
                                        sleep(500);
                                        startActivty(HomeActivity.class);
                                        finish();
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                            }.start();

//                            startActivty(HomeActivity.class);
//                            finish();
                        }
                    });
                }
            } else {
                ToastUtil.showLong("该账号未绑定房屋");
            }
        } else {
            ToastUtil.showLong("账号信息存在问题 请联系管理员");
        }
    }

    private void saveUserInfo(UserEntity userEntity) {
        Logger.e("开始保存到数据库。。。。。。。。。。。。。。" + "pwd " + pwd + " ProjectName " + userEntity.getData().getYezhuVo()
                .getXiangmuMc() + " projectNumber " + projectNumber + " accout " + accout);
        List<UserLoginInfo> userLoginInfos = DbUtils.getInstans().quaryAllUserLoginInfo();
        //查询所有已登录用户账号

        UserLoginInfo userInfo = new UserLoginInfo();
        userInfo.setIsLogin(true);
        userInfo.setPassword(pwd);
        String xiangmuMc = userEntity.getData().getYezhuVo().getXiangmuMc();
        if (TextUtils.isEmpty(xiangmuMc)) {
            if (TextUtils.isEmpty(userEntity.getData().getXiangmuVo().getLoupan())) {
                xiangmuMc = "";
            } else {
                xiangmuMc = userEntity.getData().getXiangmuVo().getLoupan();
            }
        }
        userInfo.setProjectName(xiangmuMc);
        userInfo.setProjectNumber(projectNumber);
        userInfo.setUsername(accout);

        boolean isSave = false;
        if (null != userLoginInfos && userLoginInfos.size() > 0) {
            for (UserLoginInfo userLoginInfo : userLoginInfos) {//循环遍历已存账号,否则增加
                Log.e("切换账号",
                        userLoginInfo.getUsername() + "  " + userLoginInfo.getProjectNumber());
                if (userLoginInfo.getUsername().equals(accout) && userLoginInfo.getProjectNumber().equals
                        (projectNumber)) {//如果有同手机号并且同社区的账号
                    Logger.e("如果有同手机号并且同社区的账号");
                    userLoginInfo.setIsLogin(true);
                    userLoginInfo.setPassword(pwd);
                    DbUtils.getInstans().updateOneUserLoginInfo(userLoginInfo);
                    isSave = true;//表示已存
                } else {
                    userLoginInfo.setIsLogin(false);
                    DbUtils.getInstans().updateOneUserLoginInfo(userLoginInfo);
                }
            }

            if (!isSave) {
                DbUtils.getInstans().insertOneUserLoginInfo(userInfo);
            }

        } else {//数据库中无数据,直接新增一条数据
            Logger.e("数据库中无数据,新增一条数据");
            DbUtils.getInstans().insertOneUserLoginInfo(userInfo);
        }
    }

    @Override
    public void getCodeSuccess(BaseEntity baseEntity) {
        countDownTimer.start();
    }

    @OnClick({R.id.tv_register, R.id.bt_go, R.id.img_clear})
    public void onViewClicked(View view) {
        Bundle bundle = new Bundle();
        switch (view.getId()) {
            case R.id.tv_register:
                //注册
                SpSaveUtils.putToolbarColor(2);
                startActivity(RegisterActivity.class, bundle);
//                startActivity(MainActivity.class, bundle);
//                startActivity(VideoActivity.class, bundle);
//                startActivity(CLocalDevLogin.class, bundle);
                break;
            case R.id.bt_go:
                //登录
                accout = etAccount.getText().toString().trim();
                pwd = etPwd.getText().toString().trim();
                //密码登录
//                if (TextUtils.isEmpty(accout)) {
//                    Toast.makeText(AppConfig.getInstance(), getResources().getString(R.string.请输入账号), Toast.LENGTH_LONG);
//                    return;
//                }
//                if (TextUtils.isEmpty(pwd)) {
//                    Toast.makeText(AppConfig.getInstance(), getResources().getString(R.string.请输入密码), Toast.LENGTH_LONG);
//                    return;
//                }
//
//                loginType = 1;
//                Map<String, String> map = new HashMap<>();
//                map.put("username", accout);
//                map.put("projectNumber", projectNumber);
//                map.put("loginType", "1");
//                map.put("password", EncryptUtils.encryptMD5ToString(pwd).toLowerCase());
//                mPresenter.login(map);

                startActivity(HomeActivity.class, bundle);
                break;
            case R.id.img_clear:
                //清除手机号码
                etAccount.setText("");
                break;
        }
    }

    private void openNotification() {
        NotificationManagerCompat notification = NotificationManagerCompat.from(this);
        boolean isEnabled = notification.areNotificationsEnabled();
        if (!isEnabled) {
            DialogUtils.showCommonDialog(this, "检测到您没有打开通知权限，是否打开此权限接收通知？", new DialogUtils
                    .onCommonDialogListene() {
                @Override
                public void onCommonDialogListene(View view) {
                    Intent intent = new Intent();
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
                        intent.putExtra("android.provider.extra.APP_PACKAGE", LoginActivity.this
                                .getPackageName());
                    } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {  //5.0
                        intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
                        intent.putExtra("app_package", LoginActivity.this.getPackageName());
                        intent.putExtra("app_uid", LoginActivity.this.getApplicationInfo().uid);
                        startActivity(intent);
                    } else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {  //4.4
                        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                        intent.addCategory(Intent.CATEGORY_DEFAULT);
                        intent.setData(Uri.parse("package:" + LoginActivity.this.getPackageName()));
                    } else if (Build.VERSION.SDK_INT >= 15) {
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                        intent.setData(Uri.fromParts("package", LoginActivity.this.getPackageName
                                (), null));
                    }
                    startActivity(intent);
                }
            });
        }
    }

    @Override
    protected void onDestroy() {
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
        super.onDestroy();
        mPresenter.unsubscribe();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}